import uuid, json

from flask import Blueprint, request, jsonify, Response
from service.nw_project.nw_project_service import get_all_data, get_data_by_uuid, add_data, update_data, delete_data, \
    load_file_new as load_file, clear_data, get_pagedata, get_xhlist

# app = Flask(__name__)
# 创建 Blueprint
nw_project_blueprint = Blueprint('nw_project', __name__)


# 获取所有记录
@nw_project_blueprint.route('/api/data', methods=['GET'])
def get_data():
    try:
        data = get_all_data()
        return jsonify(data), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# 获取分页记录
@nw_project_blueprint.route('/api/pagedata', methods=['POST'])
def get_pagedata_controller():
    try:
        data = request.get_json()
        l_dwbh = data.get('dwbh')
        l_model = data.get('model', '型号收支余')
        l_qzq_type = data.get('qzq_type', '科研')
        l_kjnd = data.get('kjnd')
        l_pageNum = data.get('pageNum')
        l_pageSize = data.get('pageSize')
        # print(l_dwbh, l_model, l_qzq_type, l_kjnd, l_pageNum, l_pageSize)
        data, total_count = get_pagedata(l_dwbh, l_model, l_qzq_type, l_kjnd, l_pageNum, l_pageSize)
        return jsonify(
            {"code": 200, "pageNum": l_pageNum, "pageSize": l_pageSize, "total": total_count, "data": data}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# 获取型号列表
@nw_project_blueprint.route('/api/xhlist', methods=['POST'])
def get_xhlist_controller():
    try:
        data = request.get_json()
        l_dwbh = data.get('dwbh')
        l_model = data.get('model', '型号收支余')
        l_qzq_type = data.get('qzq_type', '科研')
        l_kjnd = data.get('kjnd')
        # print(l_dwbh, l_model, l_qzq_type, l_kjnd)
        data = get_xhlist(l_dwbh, l_model, l_qzq_type, l_kjnd)
        return jsonify({"code": 200, "data": data}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@nw_project_blueprint.route('/api/load_file', methods=['GET', 'POST'])
def load_file_controller():
    data = request.json
    # ini_op.opinivalue('pz_config', **data)
    l_dwbh = data.get('dwbh')
    l_model = data.get('model', '型号收支余')
    l_qzq_type = data.get('qzq_type', '科研')
    # 动态导入内容判断模块
    from service.data_upload.file_upload import check_file_content_type
    file_content_type, file_content_type_name = check_file_content_type(data['filepath'])
    if file_content_type != 'PROJECT':
        return jsonify({"code": 500, "error": "文件内容识别失败, 请核对模板格式后重新上传"}), 500

    code = load_file(l_dwbh, l_model, l_qzq_type, data['filepath'])

    if code == 401:
        return jsonify({"code": 500, "error": "文件内容识别失败, 参考错误：缺少项目编号"}), 400
    if code == 402:
        return jsonify({"code": 500, "error": "文件内容识别失败, 参考错误：会计年度表达式不正确"}), 400
    if code == 400:
        return jsonify({"code": 500, "error": "文件内容识别失败，参考错误：会计年度等数据内容不正确"}), 400
    # 返回JSON响应
    data = json.dumps({"message": "success"}, ensure_ascii=False)
    return Response(data, content_type="application/json")


# 清空记录
@nw_project_blueprint.route('/api/clear', methods=['POST'])
def clear_data_controller():
    try:
        data = request.json
        l_dwbh = data.get('dwbh')
        l_model = data.get('model', '型号收支余')
        l_qzq_type = data.get('qzq_type', '科研')
        clear_data(l_dwbh, l_model, l_qzq_type)
        return jsonify({"code": 200, "message": "操作完成"}), 200
    except Exception as e:
        return jsonify({"code": 500, "error": str(e)}), 500


# 获取单条记录
@nw_project_blueprint.route('/api/data/<string:uuid>', methods=['GET'])
def get_single_data(uuid):
    try:
        data = get_data_by_uuid(uuid)
        if data:
            return jsonify(data), 200
        else:
            return jsonify({"message": "Data not found"}), 404
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# 添加记录
@nw_project_blueprint.route('/api/data', methods=['POST'])
def add_new_data():
    try:
        data = request.get_json()
        dwbh = data.get('dwbh')
        code = data.get('code')
        name = data.get('name')
        qzq_type = data.get('qzq_type', 'KY')
        model = data.get('model')
        status = data.get('status', '1')  # 默认值是 '1'
        create_by = data.get('create_by', 'admin')
        remarks = data.get('remarks')

        add_data(uuid.uuid4(), dwbh, model, code, name, qzq_type, status, create_by, remarks)
        return jsonify({"message": "Data added successfully!"}), 201
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# 更新记录
@nw_project_blueprint.route('/api/data/<string:uuid>', methods=['PUT'])
def update_existing_data(uuid):
    try:
        data = request.get_json()
        dwbh = data.get('dwbh')
        code = data.get('code')
        name = data.get('name')
        qzq_type = data.get('qzq_type', 'KY')
        model = data.get('model')
        status = data.get('status', '1')  # 默认值是 '1'
        create_by = data.get('create_by', 'admin')
        remarks = data.get('remarks')

        update_data(uuid, dwbh, model, code, name, qzq_type, status, create_by, remarks)
        return jsonify({"message": "Data updated successfully!"}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# 删除记录
@nw_project_blueprint.route('/api/data/<string:uuid>', methods=['DELETE'])
def delete_existing_data(uuid):
    try:
        delete_data(uuid)
        return jsonify({"message": "Data deleted successfully!"}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500


if __name__ == '__main__':
    # 在应用启动时创建表
    from service.nw_project.nw_project_service import create_table

    create_table()
    # app.run(debug=True)
